﻿using CMS.Excep;
using CMS.Utils;
using Microsoft.Data.Sqlite;
using System.Reflection;
using System.Text;

namespace CMS.DataAccess
{
    public class DbFuzzyQuery
    {
        List<PropValueSetter> PropSetters;
        string tableName;
        Type type;
        DbInstance instance;
        StringBuilder whereSqls = new StringBuilder(" WHERE DEL = 'N' ");
        public DbFuzzyQuery(DbInstance instance, Type type)
        {
            this.instance = instance;
            this.type = type;
            var tabname = type.GetCustomAttribute<MyTableNameAttribute>()?.TableName;
            if (tabname == null) throw new MyOptException($"{type.Name}不支持FuzzyQuery");
            tableName = tabname!;
        }
        public DbFuzzyQuery Where(string sql)
        {
            whereSqls.Append(" AND " + sql);
            return this;
        }
        public object GetField(string field,string pk)
        {
            string sql = string.Format("SELECT {1} FROM \"{0}\" WHERE DEL = 'N' AND PK = @PK", tableName, field);
            using (var cmd = instance.MakeCommand(sql, new SqliteParameter("@PK", pk)))
            {
                var result = cmd.ExecuteScalar();
                return result;
            }
        }
    }
}
